<!-- 学社 - 考试 - 答题页 -->
<template>
  <view class="pb-20">
    <z-navbar :title="state.detailData?.paper_name" :border-bottom="true" :custom-back="onBack"></z-navbar>
    <!-- 进入即开始倒计时 倒计时结束自动提交 -->
    <view class="fixed left-0 w-full h-60 bg-#F4AF22 flex justify-center items-center c-white text-28" :style="{ top: backIconHeight + 44 + 'px' }">{{ state.countDown }}</view>
    <view class="px-4 pt-8">
      <view class="my-3 flex justify-between">
        <view class="flex-1 c-#666 text-32 text-center text-single"><text class="c-#333 font-bold">分类：</text>{{
          state.detailData?.category?.name }}</view>
        <view class="flex-1 c-#666 text-32 text-center"><text class="c-#333 font-bold">题数：</text>{{
          state.detailData?.single_number + state.detailData?.multiple_number }}</view>
        <view class="flex-1 c-#666 text-32 text-center"><text class="c-#333 font-bold">总分：</text>{{
          state.detailData?.total_score }}</view>
      </view>
      <!-- 单选题目部分 -->
      <template v-if="state.singleQustionList.length > 0">
        <view class="font-bold c-#333 text-32">一、单选题</view>
        <view v-for="(item, index) in state.singleQustionList" :key="index" class="px-7">
          <!-- 题目 -->
          <view class="py-1">{{ `${index + 1}、${item.content}` }}</view>
          <!-- 选项 -->
          <u-radio-group v-model="item.checked" active-color="#F4AF22" wrap :size="40">
            <u-radio v-for="(options, index) in item.options" :key="index" :name="options.sort">
              {{ `${options.sort}、${options.title}` }}
            </u-radio>
          </u-radio-group>
        </view>
      </template>
      <!-- 多选题目部分 -->
      <template v-if="state.multipleQustionList.length > 0">
        <view class="font-bold c-#333 text-32">二、多选题</view>
        <view v-for="(item, index) in state.multipleQustionList" :key="index" class="px-7">
          <!-- 题目 -->
          <view class="py-1">{{ `${index + 1}、${item.content}` }}</view>
          <u-checkbox-group wrap size="40">
            <u-checkbox v-for="(options, index) in item.options" :key="index" v-model="options.checked" shape="circle"
              active-color="#F4AF22" :name="options.sort"> {{ `${options.sort}、${options.title}` }}</u-checkbox>
          </u-checkbox-group>
        </view>
      </template>
    </view>
    <view class="bottom-wrap-16 bg-white">
      <u-line class="w-full" color="#eee" :hair-line="false" />
      <view class="btn-submit" @click="onSubmit">提交</view>
    </view>
  </view>
</template>
<script setup>
import { showToast, showModal } from '@/common/util/uni'
import { getExamDetail, getExamQuestion, postExamHandIn } from '@/common/http/module/society.js'
import dayjs from 'dayjs'
import customParseFormat from 'dayjs/plugin/customParseFormat';
import duration from 'dayjs/plugin/duration';
dayjs.extend(duration)
dayjs.extend(customParseFormat)

const state = reactive({
  detailData: null, // 试卷详情
  club_id: '', // 学社id
  exam_id: '', // 试卷id
  questionList: [], // 试题数据
  singleQustionList: [], // 单选题
  multipleQustionList: [], // 多选题
  duration: '', // 考试时长
  durationStr: '', // 考试时长 时分秒字符串格式
  initSeconds: '', // 初始总秒数
  totalSeconds: '', // 总秒数
  countDown: '', // 倒计时
  timeInterval: null // 定时器
})

const backIconHeight = uni.getMenuButtonBoundingClientRect().top

function loadData () {
  getExamQuestion(state.exam_id).then(res => {
    state.questionList = res.data
    countDownStart()
    // 单选
    state.singleQustionList = state.questionList.filter(v => v.type == 0)
    // 多选
    state.multipleQustionList = state.questionList.filter(v => v.type == 1)
  })
}

function onBack () {
  showModal({
    content: '是否放弃考试？',
    confirmText: '否',
    cancelText: '是',
    success: ({ confirm }) => {
      if (confirm) return;
      uni.navigateBack()
    },
  });
}

function countDownStart () {
  state.timeInterval = setInterval(() => {
    if (state.totalSeconds > 0) {
      state.totalSeconds--
      formatTime(state.totalSeconds)
    } else {
      // 倒计时结束自动提交考试
      clearInterval(state.timeInterval)
      onSubmit()
    }
  }, 1000)
}

function formatTime (totalSeconds) {
  state.duration = dayjs.duration(totalSeconds, 'seconds')
  state.countDown = state.duration.format('HH:mm:ss')
}

function onSubmit () {
  // 没答的题答案传空
  const singleAnsers = state.singleQustionList.map(v => {
    return {
      question_id: v.id,
      answer: v?.checked ?? ''
    }
  })
  const multipleAnsers = state.multipleQustionList.map(v => {
    return {
      question_id: v.id,
      answer: v.options.filter(o => o.checked).map(v => v.sort).join(',') ?? ''
    }
  })
  const data_info = [...singleAnsers, ...multipleAnsers]
  postExamHandIn({
    club_id: state.club_id,
    exam_id: state.exam_id,
    exam_log_id: '', // 考试记录id（如果是重新考试的话必传）
    exam_time: state.initSeconds - state.totalSeconds,
    data_info
  }).then(res => {
    showToast('提交成功')
    setTimeout(() => {
      // 提交成功后关闭开始页 防止重复提交
      uni.redirectTo({
        url: `/package_society/pages/exam/testing/result?data=${encodeURIComponent(JSON.stringify(res.data))}&club_id=${state.club_id}&duration=${state.durationStr}`
      })
    }, 600)
  })
}

// 获取试卷详情
async function loadDetail () {
  const { data } = await getExamDetail(state.club_id, state.exam_id)
  state.detailData = data
}

onLoad(options => {
  state.club_id = options.club_id
  state.exam_id = options.exam_id
  state.durationStr = options.duration
  state.exam_log_id = options?.exam_log_id ?? ''
  // 时间戳(秒)
  const timeObj = dayjs(options.duration, 'HH:mm:ss')
  const hours = timeObj.hour()
  const minutes = timeObj.minute()
  const seconds = timeObj.second()
  // 初始总秒数，提交时要算答题秒数
  state.totalSeconds = hours * 60 * 60 + minutes * 60 + seconds
  state.initSeconds = state.totalSeconds
  formatTime(state.totalSeconds)
  loadDetail()
  loadData()
})

// 离开清除定时器
// onHide(() => {
//   clearInterval(state.timeInterval)
// })

onUnload(() => {
  clearInterval(state.timeInterval)
})
</script>

<style lang="scss" scoped>
:deep(.u-radio) {
  padding-top: 10rpx;
  padding-bottom: 10rpx;
}

:deep(.u-radio__icon-wrap) {
  width: 40rpx !important;
  height: 40rpx !important;
}

:deep(.u-checkbox) {
  padding-top: 10rpx;
  padding-bottom: 10rpx;
}
</style>
